package com.hwpt.chesedemo.utils

import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp

@Composable
fun FormattedResponseText(
    response: String,
    isStreamComplete: Boolean,
    isLoading: Boolean
) {
    val formattedText = remember(response, isStreamComplete) {
        if (isStreamComplete || !isLoading) {
            // 流式完成或不在加载中时，显示完整格式化文本
            formatMarkdownText(response)
        } else {
            // 流式进行中时，显示原始文本（避免频繁格式化开销）
            response
        }
    }

    Text(
        text = buildAnnotatedString {
            append(formattedText)
        },
        fontSize = 16.sp,
        color = Color.White,
        textAlign = TextAlign.Start,
        lineHeight = 24.sp
    )
}

// 简单的 Markdown 格式化函数
private fun formatMarkdownText(text: String): String {
    var formatted = text
    
    // 替换 Markdown 粗体
    formatted = formatted.replace("\\*\\*(.*?)\\*\\*".toRegex()) { matchResult ->
        matchResult.groupValues[1] // 移除 **，直接显示文本
    }
    
    // 替换 Markdown 标题
    formatted = formatted.replace("### (.*)".toRegex()) { matchResult ->
        "\n${matchResult.groupValues[1]}\n" // 将 ### 标题转换为换行
    }
    
    // 清理多余的空行
    formatted = formatted.replace("\n\\s*\n".toRegex(), "\n\n")
    
    return formatted.trim()
}